﻿/**
 * 
 */
package com.roc.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.roc.dao.DaoException;
import com.roc.dao.IBaseDao;
import com.roc.pojo.SysLog;
import com.roc.util.PageUtil;

/**
 * @author Administrator
 * 
 */
@Repository("baseDao")
public class BaseDaoImpl implements IBaseDao {

	static Logger logger = LogManager.getLogger(BaseDaoImpl.class);

	@Autowired
	protected SessionFactory sessionFactory;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.dao.IBaseDao#editSave(java.io.Serializable)
	 */
	public void editSave(Serializable object) throws DaoException {
		Session session =null;
		try {
			session= sessionFactory.getCurrentSession();
			session.save(object);
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("保存对象失败" + object, e);
		}finally {
			session.flush();
			session.evict(object);
			session.clear();
		}
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.dao.IBaseDao#editUpdate(java.io.Serializable)
	 */
	public void editUpdate(Serializable object) throws DaoException {
		try {
			Session session = sessionFactory.getCurrentSession();
			session.clear();
			session.update(object);
			session.flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("修改对象失败" + object, e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.dao.IBaseDao#edit(java.io.Serializable)
	 */
	public void edit(Serializable object) throws DaoException {
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(object);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("编辑对象失败" + object, e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.dao.IBaseDao#delete(java.io.Serializable)
	 */
	public void delete(Serializable object) throws DaoException {
		try {
			sessionFactory.getCurrentSession().delete(object);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("删除对象失败" + object, e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.dao.IBaseDao#queryAll(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public List<Object> queryAll(String hql) throws DaoException {
		try {
			return sessionFactory.getCurrentSession().createQuery(hql).list();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}

	}
	public List<Object> queryAll(String hql,Object[] param) throws DaoException {
		Session session=null;
		try {
			session=sessionFactory.getCurrentSession();
			Query query=session.createQuery(hql);
			if(param!=null&&param.length>0){
				for(int i=0;i<param.length;i++){
					query.setParameter(i, param[i]);
				}
			}
			return query.list();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}finally {
			 
			session.clear();
		}
	}
	public List queryByPage(String hql, PageUtil page) throws DaoException {
		try {
			return getResultList(queryAll(hql), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}

	}

	public List createSQLQuery(String hql) throws DaoException {
		try {
			return sessionFactory.getCurrentSession().createSQLQuery(hql)
					.list();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}
	}

	public List createSQLQueryByPage(String hql, PageUtil page)
			throws DaoException {
		try {
			return getResultList(createSQLQuery(hql), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}

	}

	private List getResultList(List totalList, PageUtil page) {
		if (totalList.size() < 1) {
			return totalList;
		}
		if (page == null) {
			page = new PageUtil();
		}
		page.setTotalPage(totalList.size());
		List result = null;
		if (page.getCurrentEnd() > totalList.size()) {
			result = totalList
					.subList(page.getCurrentStart(), totalList.size());
		} else {
			result = totalList.subList(page.getCurrentStart(), page
					.getCurrentEnd());
		}
		return result;
	}

	public void updateSQLQuery(String hql) throws DaoException {
		try {
			sessionFactory.getCurrentSession().createSQLQuery(hql)
					.executeUpdate();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}

	}

	public void updateQuery(String hql) throws DaoException {
		try {
			sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.dao.IBaseDao#queryAll(java.lang.String, int, int)
	 */
	public List queryAll(String hql, int first, int max) throws DaoException {
		try {
			Query query = sessionFactory.getCurrentSession().createQuery(hql);
			query.setFirstResult(first);
			query.setMaxResults(max);
			return query.list();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL分页失败[" + hql + "][first=" + first
					+ "][max=" + max + "]", e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.dao.IBaseDao#queryAll(java.lang.Class)
	 */
	public List queryAll(Class object) throws DaoException {
		try {
			return sessionFactory.getCurrentSession().createCriteria(object)
					.list();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询对象失败[" + object + "]", e);
		}
	}

	public Object createSQLQueryUniqueResult(String hql) throws DaoException {
		try {
			return sessionFactory.getCurrentSession().createSQLQuery(hql)
					.uniqueResult();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}
	}

	public Object createQueryUniqueResult(String hql) throws DaoException {
		try {
			return sessionFactory.getCurrentSession().createQuery(hql)
					.uniqueResult();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}
	}
	 
	public Object createQueryUniqueResult(String hql, Object[] param) throws DaoException {
		try {
			Session session=sessionFactory.getCurrentSession();
			Query  query=session.createQuery(hql);
			
			if(param!=null&&param.length>0){
				for(int i=0;i<param.length;i++){
					query.setParameter(i, param[i]);
				}
			}
			return query.uniqueResult();
		} catch (HibernateException e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询HQL失败[" + hql + "]", e);
		}
	}
	

	@Override
	public void addSyslog(String code, String codeName, String operators,
			String context) throws DaoException {
		
		try {
			SysLog sysLog=new SysLog();
			sysLog.setOper_code(code);
			sysLog.setOper_name(codeName);
			sysLog.setOperators(operators);
			if(context!=null&&context.length()>250){
				sysLog.setLog_context(context.substring(0,246)+"...");
			}else {
				sysLog.setLog_context(context);
			}
			
			Session session = sessionFactory.getCurrentSession();
			session.save(sysLog);
			session.flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("保存操作日志失败", e);
		}
		
	}

	@Override
	public Object loadById(long id, Class c) throws DaoException {
		
		Object obj=null;
		try {
			Session session = sessionFactory.getCurrentSession();
			obj = session.get(c, id);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new DaoException("查询数据出错", e);
		}
		return obj;
	}

	

}
